package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.dao.*;
import com.changgou.goods.pojo.*;
import com.changgou.goods.service.SpuService;
import com.changgou.util.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    /***
     * 查询全部列表
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /***
     * 根据ID查询
     * @param spuId
     * @return
     */
    @Override
    public Goods findById(String spuId) {
        Goods goods = new Goods();
        //1.spu
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        goods.setSpu(spu);

        //2.sku
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId", spuId);
        List<Sku> skuList = skuMapper.selectByExample(example);
        goods.setSkuList(skuList);

        return goods;
    }


    @Autowired
    private IdWorker idWorker;

    /***
     * 增加
     * @param goods
     */
    @Override
    @Transactional
    public void add(Goods goods) {
        //1.存spu
        Spu spu = goods.getSpu();
        //id
        String supId = idWorker.nextId() + "";
        spu.setId(supId);
        //是否上架
        spu.setIsMarketable("0");
        //是否下架
        spu.setIsDelete("0");
        //是否通过审核
        spu.setIsEnableSpec("0");
        spuMapper.insertSelective(spu);

        //2.存sku
        this.saveSkuList(goods);
    }

    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    //存sku方法
    private void saveSkuList(Goods goods) {

        Spu spu = goods.getSpu();
        String spuName = spu.getName();
        String spuId = spu.getId();

        Integer category3Id = spu.getCategory3Id();
        Category category = categoryMapper.selectByPrimaryKey(category3Id);
        String categoryName = category.getName();

        Integer brandId = spu.getBrandId();
        Brand brand = brandMapper.selectByPrimaryKey(brandId);
        String brandName = brand.getName();

        //获取sku集合
        List<Sku> skuList = goods.getSkuList();
        if (skuList != null) {
            //遍历sku集合,循环填充数据并添加到数据库中
            for (Sku sku : skuList) {
                //1.id
                String skuId = idWorker.nextId() + "";
                sku.setId(skuId);
                //2.name spu名称+" "+spec属性+" "spec属性
                String spec = sku.getSpec();
                //json转换防止出错
                if (StringUtils.isEmpty(spec)) {
                    sku.setSpec("{}");
                }
                Map<String, String> map = JSON.parseObject(spec, Map.class);
                String skuName = spuName;
                for (String value : map.values()) {
                    skuName += " " + value;
                }
                sku.setName(skuName);
                //3.1.创建时间
                sku.setCreateTime(new Date());
                //3.2.修改时间
                sku.setUpdateTime(new Date());
                //4.spuId
                sku.setSpuId(spuId);
                //5.1.分类id
                sku.setCategoryId(category3Id);
                //5.2.分类名称
                sku.setCategoryName(categoryName);
                //6.品牌名称
                sku.setBrandName(brandName);
                //把每一个sku存入数据库
                skuMapper.insertSelective(sku);
            }
        }
        //分类和品牌关联关系
        //查一下原先有没有关系 sleect count(*)
        CategoryBrand categoryBrand = new CategoryBrand();
        categoryBrand.setCategoryId(category3Id);
        categoryBrand.setBrandId(brandId);
        int count = categoryBrandMapper.selectCount(categoryBrand);
        //没有关系,增加关系
        if (count == 0) {
            categoryBrandMapper.insertSelective(categoryBrand);
        }
    }


    /***
     * 修改
     * @param goods
     */
    @Override
    public void update(Goods goods) {
        //1.修改spu
        Spu spu = goods.getSpu();
        spuMapper.updateByPrimaryKeySelective(spu);
        //2.修改sku
        //2.1 关联的skuList删除
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId", spu.getId());
        skuMapper.deleteByExample(example);
        //2.2 skuList增加
        saveSkuList(goods);
    }

    /***
     * 逻辑删除
     * @param id
     */
    @Override
    @Transactional
    public void delete(String id) {
        //1.查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null) {
            throw new RuntimeException("商品不存在");
        }
        //2.删除前商品为下架状态
        if (!spu.getIsMarketable().equals("0")) {
            throw new RuntimeException("商品未下架");
        }
        //3.1 逻辑删除状态改为 1
        spu.setIsDelete("1");
        //3.2 商品审核状态改为 0
        spu.setStatus("0");

        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /***
     * 物理删除
     * @param id
     */
    @Override
    @Transactional
    public void realDel(String id) {
        //1.查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null) {
            throw new RuntimeException("商品不存在");
        }
        //2.必须是已删除状态
        if (!spu.getIsDelete().equals("1")) {
            throw new RuntimeException("商品不是已删除状态,不能移除");
        }
        //3.物理删除
        spuMapper.deleteByPrimaryKey(id);
    }


    /***
     * 条件查询
     * @param searchMap
     * @return
     */
    @Override
    public List<Spu> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /***
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Spu> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        return (Page<Spu>) spuMapper.selectAll();
    }

    /***
     * 条件+分页查询
     * @param searchMap 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public Page<Spu> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        return (Page<Spu>) spuMapper.selectByExample(example);
    }

    /***
     * 商品审核
     * @param id
     */
    @Override
    @Transactional
    public void audit(String id) {
        //1.查询spu对象
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null) {
            throw new RuntimeException("商品不存在");
        }
        //2.判断spu是否删除
        String isDelete = spu.getIsDelete();
        if ("1".equals(isDelete)) {
            throw new RuntimeException("商品已删除!");
        }
        //3.不是删除状态 则审核通过 状态为1,自动上架1
        spu.setStatus("1");
        spu.setIsMarketable("1");

        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /***
     * 商品下架
     * @param id
     */
    @Override
    @Transactional
    public void pull(String id) {
        //1.查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null) {
            throw new RuntimeException("商品不存在");
        }
        //2.判断spu是否删除
        String isDelete = spu.getIsDelete();
        if ("1".equals(isDelete)) {
            throw new RuntimeException("商品已删除!");
        }
        //3.不是删除状态 则审核通过 状态为0,自动下架
        spu.setIsMarketable("0");

        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /***
     * 商品上架
     * @param id
     */
    @Override
    @Transactional
    public void put(String id) {
        //1.查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null) {
            throw new RuntimeException("商品不存在");
        }
        //2.检查商品是否通过审核
        if (!spu.getStatus().equals("1")) {
            throw new RuntimeException("商品未审核");
        }
        //3.修改上架状态为1
        spu.setIsMarketable("1");

        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /***
     * 商品还原(被逻辑删除)
     * @param id
     */
    @Override
    @Transactional
    public void restore(String id) {
        //1.查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null) {
            throw new RuntimeException("商品不存在");
        }
        //2.检查商品是否处于删除状态
        if (!spu.getIsDelete().equals("1")) {
            throw new RuntimeException("商品未删除");
        }
        //3.1 删除状态 0
        spu.setIsDelete("0");
        //3.2 审核状态 0
        spu.setStatus("0");

        //4.存入数据库
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /***
     * 根据ID查询数据
     * @param spuId
     * @return
     */
    @Override
    public Spu findSpuById(String spuId) {
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        return spu;
    }

    /***
     * 构建查询对象
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 主键
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andEqualTo("id", searchMap.get("id"));
            }
            // 货号
            if (searchMap.get("sn") != null && !"".equals(searchMap.get("sn"))) {
                criteria.andEqualTo("sn", searchMap.get("sn"));
            }
            // SPU名
            if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                criteria.andLike("name", "%" + searchMap.get("name") + "%");
            }
            // 副标题
            if (searchMap.get("caption") != null && !"".equals(searchMap.get("caption"))) {
                criteria.andLike("caption", "%" + searchMap.get("caption") + "%");
            }
            // 图片
            if (searchMap.get("image") != null && !"".equals(searchMap.get("image"))) {
                criteria.andLike("image", "%" + searchMap.get("image") + "%");
            }
            // 图片列表
            if (searchMap.get("images") != null && !"".equals(searchMap.get("images"))) {
                criteria.andLike("images", "%" + searchMap.get("images") + "%");
            }
            // 售后服务
            if (searchMap.get("saleService") != null && !"".equals(searchMap.get("saleService"))) {
                criteria.andLike("saleService", "%" + searchMap.get("saleService") + "%");
            }
            // 介绍
            if (searchMap.get("introduction") != null && !"".equals(searchMap.get("introduction"))) {
                criteria.andLike("introduction", "%" + searchMap.get("introduction") + "%");
            }
            // 规格列表
            if (searchMap.get("specItems") != null && !"".equals(searchMap.get("specItems"))) {
                criteria.andLike("specItems", "%" + searchMap.get("specItems") + "%");
            }
            // 参数列表
            if (searchMap.get("paraItems") != null && !"".equals(searchMap.get("paraItems"))) {
                criteria.andLike("paraItems", "%" + searchMap.get("paraItems") + "%");
            }
            // 是否上架
            if (searchMap.get("isMarketable") != null && !"".equals(searchMap.get("isMarketable"))) {
                criteria.andEqualTo("isMarketable", searchMap.get("isMarketable"));
            }
            // 是否启用规格
            if (searchMap.get("isEnableSpec") != null && !"".equals(searchMap.get("isEnableSpec"))) {
                criteria.andEqualTo("isEnableSpec", searchMap.get("isEnableSpec"));
            }
            // 是否删除
            if (searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete"))) {
                criteria.andEqualTo("isDelete", searchMap.get("isDelete"));
            }
            // 审核状态
            if (searchMap.get("status") != null && !"".equals(searchMap.get("status"))) {
                criteria.andEqualTo("status", searchMap.get("status"));
            }

            // 品牌ID
            if (searchMap.get("brandId") != null) {
                criteria.andEqualTo("brandId", searchMap.get("brandId"));
            }
            // 一级分类
            if (searchMap.get("category1Id") != null) {
                criteria.andEqualTo("category1Id", searchMap.get("category1Id"));
            }
            // 二级分类
            if (searchMap.get("category2Id") != null) {
                criteria.andEqualTo("category2Id", searchMap.get("category2Id"));
            }
            // 三级分类
            if (searchMap.get("category3Id") != null) {
                criteria.andEqualTo("category3Id", searchMap.get("category3Id"));
            }
            // 模板ID
            if (searchMap.get("templateId") != null) {
                criteria.andEqualTo("templateId", searchMap.get("templateId"));
            }
            // 运费模板id
            if (searchMap.get("freightId") != null) {
                criteria.andEqualTo("freightId", searchMap.get("freightId"));
            }
            // 销量
            if (searchMap.get("saleNum") != null) {
                criteria.andEqualTo("saleNum", searchMap.get("saleNum"));
            }
            // 评论数
            if (searchMap.get("commentNum") != null) {
                criteria.andEqualTo("commentNum", searchMap.get("commentNum"));
            }

        }
        return example;
    }

}
